﻿using MobaCommon.Code;
using MobaCommon.Dto;
using MobaCommon.OpCode;
using Photon.SocketServer;
using System;
using System.Collections.Generic;
using System.Text;
using LitJson;
using MOBAServer.Cache;

namespace MOBAServer.Logic
{
    /// <summary>
    /// 账号的逻辑处理
    /// </summary>
    class AccountHandler : SingeSend,IOpHandler
    {
        //账号缓存
        private AccountCache cache = Caches.Account;
        public void OnDisconnect(MobaClient client)
        {
            cache.OffLine(client);
        }

        public void OnRequest(MobaClient client, byte subCode, OperationRequest request)
        {
            switch(subCode)
            {
                case OpAccount.login:
                    AccountDto loginAccountDto = JsonMapper.ToObject<AccountDto>(request[0].ToString());
                    OnLogin(client,loginAccountDto.Account, loginAccountDto.Password);

                    break;
                case OpAccount.register:
                    AccountDto registerAccountDto = JsonMapper.ToObject<AccountDto>(request[0].ToString());
                    OnRegister(client,registerAccountDto.Account,registerAccountDto.Password);

                    break;
                default:break;
            }
        }
        #region 子处理
        /// <summary>
        /// 登录的处理
        /// </summary>
        /// <param name="acc"></param>
        /// <param name="pwd"></param>
        private void OnLogin(MobaClient client,string acc, string pwd)
        {
            //无效检测
            if (string.IsNullOrEmpty(acc) || string.IsNullOrEmpty(pwd))
            {
                return;
            }
            if(cache.IsOnline(acc))
            {
                this.Send(client,OpCode.AccountCode,OpAccount.login,-1,"玩家在线");
                return;
            }
            //验证账号密码是否合法
            if(cache.Match(acc, pwd))
            {
                cache.OnLine(acc,client);
                this.Send(client, OpCode.AccountCode, OpAccount.login, 0, "登录成功");

            }
            else
            {
                this.Send(client, OpCode.AccountCode, OpAccount.login, -2, "账号或密码错误");
            }
        }
        /// <summary>
        /// 注册的处理
        /// </summary>
        /// <param name="acc"></param>
        /// <param name="pwd"></param>
        private void OnRegister(MobaClient client,string acc, string pwd)
        {
            //无效检测
            if(string.IsNullOrEmpty(acc)||string.IsNullOrEmpty(pwd))
            {
                return;
            }
            //重复检测
            if(cache.Has(acc))
            {
                this.Send(client,OpCode.AccountCode,OpAccount.register,-1,"注册失败,已有账号");
                return;
            }
            cache.Add(acc, pwd);
            this.Send(client, OpCode.AccountCode, OpAccount.register, 0, "注册成功");
           
        } 
        #endregion
    }
}
